import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/call_uil.dart';
import 'package:yuan_hang_app/utils/event_bus.dart';
import 'package:yuan_hang_app/utils/jmessage_helper.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/enter/view/login_page.dart';
import 'package:yuan_hang_app/views/enter/view/main_page.dart';
import 'package:yuan_hang_app/views/msg/alert_msg_page.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import 'http/api.dart';
import 'http/http_utils.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  GestureBinding.instance.resamplingEnabled = true;
  await SpUtil.getInstance();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var bus = EventBus();

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.width;
    bool isLogin =
        StringUtils.isEmpty(SpUtil.getString(WConstant.USERINFO) ?? "");

    /// print("========================${SpUtil.getString(WConstant.USERINFO)}");
    return ScreenUtilInit(
      designSize: Size(screenWidth, screenHeight),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: WColors.primaryColor),
          useMaterial3: true,
        ),
        builder: BotToastInit(),
        debugShowCheckedModeBanner: false,
        navigatorKey: WConstant.navigatorKey,
        // debug 标签设置这一属性即可
        navigatorObservers: [BotToastNavigatorObserver()],
        localizationsDelegates: const [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate
        ],
        routes: {
          '/loginPage': (ctx) => const LoginPage(),
          '/alertMsgPage': (ctx) => const AlertMsgPage()
        },
        supportedLocales: const [
          Locale('en', 'US'),
          Locale('zh', 'CH'),
        ],
        home: isLogin ? const LoginPage() : const MainPage(),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WConstant.appContext = context;
    setPush();
    getUnreadCount();
  }

  void setPush() {
    JmessageHelper.initPush();

    ///通知栏消息
    JmessageHelper.addListenerEventHandler(receiveNotify: (message) {
      ///收到消息监听
      Map msg = JmessageHelper.getExtras(message);
      print("messagegegegegeg: ${msg}");
      getUnreadCount();

    }, onOpenNotify: (message) {
      ///打开通知栏监听
      Map msg = JmessageHelper.getExtras(message);
      print("点击-----$message");
      WConstant.navigatorKey.currentState?.pushNamed('/alertMsgPage');
    }, onInAppMessageShow: (message) {
      Map msg = JmessageHelper.getExtras(message);
      print("=====角标在这块: ${msg}");
      //  getUnreadCount();
    });
    //获取 iOS 点击推送启动应用的那条通知。
    // JPush().getLaunchAppNotification().then((message) {
    //   if (message.isNotEmpty) {
    //     WConstant.navigatorKey.currentState?.pushNamed('/alertMsgPage');
    //   }
    // });
  }

  void getUnreadCount() {
    HttpUtils()
        .get(
            "${Api.getNoticeMessageCount}?userId=${WConstant().userInfo.userId}")
        .then((value) {
      if (value.resultCode == 200 && value.data["resultCode"] == 200) {
        var msgCount = value.data["data"];
        int count = msgCount?['taskNum'] ?? 0;
        bus.emit("noticeReadCount", msgCount);
        if (Platform.isAndroid) {
          FlutterAppBadger.updateBadgeCount(count);
        } else if (Platform.isIOS) {
          JPush().setBadge(count);
        }
        setState(() {});
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    }).catchError((e) {});
  }

  @override
  void dispose() {
    super.dispose();
  }
}
